<!-- 景点的评论组件 -->
<template>
  <div class="comments-section">
    <!-- 评分汇总 -->
    <div class="rating-summary">
      <div class="rating-row-1">
        <div class="score-box">
          <span class="sort-get-score">{{ rating }}</span>
          <span class="sort-all-score">/5</span>
        </div>
        <span class="entity-name">{{  ratingComment(props.rating) }}</span>
        <span class="total-reviews">{{ totalReviews }} 条评价</span>
        <el-button type="primary" :icon="EditIcon" @click="writeReview" class="write-review-button">
          撰写评价
        </el-button>
      </div>
      
      <div class="filter-tabs">
        <span
          v-for="(filter, index) in filters"
          :key="index"
          :class="{ active: activeFilter === filter.type }"
          @click="applyFilter(filter.type)"
        >
          {{ filter.label }}
        </span>
      </div>
    </div>

    <!-- 评论列表 -->
    <div class="comments-list">
      <div
        v-for="(comment, index) in displayedComments"
        :key="index"
        class="comment"
      >
        <div class="comment-header">
          <img :src="comment.user?.avatar || defaultAvatar" class="avatar" alt="User Avatar" />
          <span class="username">{{ comment.user?.userName }}</span>
        </div>
        <div class="comment-body">
          <div class="rating-comment">
            <div class="rating-box">
                    <el-rate
                        v-model=comment.score
                        disabled
                        show-score
                        text-color="#F5F5F5"
                        :colors="['#FF0000', '#FFCC00', '#00CC00']"
                        score-template="{value} / 5"
                    />
            </div>
            <span class="rating-comment-text">{{  ratingComment(comment.score) }}</span>
          </div>
          <p class="comment-text" :class="{ expanded: comment.expanded }">
            {{ comment.expanded ? comment.text : truncatedText(comment.remark) }}
          </p>
          <span class="toggle-text" v-if="comment.remark?.length > 230" @click="toggleComment(comment)">
            {{ comment.expanded ? '折叠评论' : '展示全部' }}
          </span>
          <div class="attached-images" v-if="comment.picture?.length > 0">
            <img
              v-for="(img, imgIndex) in comment.picture"
              :key="imgIndex"
              :src="img"
              class="thumbnail"
              alt="Attached Image"
            />
          </div>
          <div class="like-and-time">
            <span class="like-button">
              <i class="fas fa-thumbs-up"></i> {{ comment.reLike }}
            </span>
            <span class="timestamp">评价日期 {{ comment.reDate}}</span>
          </div>
          <!-- 子评论列表 -->
<!-- 子评论区 -->
<div class="child-comments" v-if="comment.comments && comment.comments.length > 0">
  <div
    class="comment child-comment"
    v-for="(child, childIndex) in comment.comments"
    :key="childIndex"
  >
    <div class="comment-header">
      <img :src="child.user?.avatar || defaultAvatar" class="avatar" alt="User Avatar" />
      <span class="username">{{ child.user?.userName }}</span>
    </div>
    <div class="comment-body">
      <p class="comment-text">{{ child.remark }}</p>
      <div class="like-and-time">
        <span class="like-button">
          <i class="fas fa-thumbs-up"></i> {{ child.reLike }}
        </span>
        <span class="timestamp">评价日期 {{ child.reDate }}</span>
      </div>
    </div>
  </div>
</div>


        </div>
      </div>
      <hr v-if="index < displayedComments.length - 1" />
    </div>

    <div class="pagination">
        <el-pagination
            layout="prev, pager, next"
            :total="totalComments"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="handlePageChange"
        ></el-pagination>
    </div>
    
  </div>
</template>

<script setup>
import router from '@/router';
import { ref, computed ,watch,onMounted} from 'vue';
import { defineProps } from 'vue';
import EditIcon from './icons/EditIcon.vue';

const props = defineProps({
  rating: {
    type: Number,
    default: 4.8,
  },
  totalReviews: {
    type: Number,
    default: 134994,
  },
  comments: {
    type: Array,
    default: () => [],
  },
});


// 初始打印
onMounted(() => {
  console.log('初始 rating:', props.rating);
  console.log('初始 totalReviews:', props.totalReviews);
  console.log('初始 comments:', props.comments);
});

// 监听 rating
watch(
  () => props.rating,
  (newVal, oldVal) => {
    console.log('rating 发生变化:', oldVal, '=>', newVal);
  }
);

// 监听 totalReviews
watch(
  () => props.totalReviews,
  (newVal, oldVal) => {
    console.log('totalReviews 发生变化:', oldVal, '=>', newVal);
  }
);

// 监听 comments
watch(
  () => props.comments,
  (newVal, oldVal) => {
    console.log('comments 发生变化:');
    console.log('旧值:', oldVal);
    console.log('新值:', newVal);
  },
  { deep: true } // 如果 props.comments 是对象数组，开启深度监听
);


const currentPage = ref(1);
const pageSize = ref(8);
const activeFilter = ref('all');

const filters = computed(() => [
  { type: 'all', label: `全部 (${props.comments.length})` },
  { type: 'latest', label: '最新' },
  {
    type: 'withImages',
    label: `附图 (${props.comments.filter(c => c.picture?.length > 0).length})`,
  },
  {
    type: 'positive',
    label: `好评 (${props.comments.filter(c => c.score >= 4).length})`,
  },
  {
    type: 'negative',
    label: `差评 (${props.comments.filter(c => c.score <= 2).length})`,
  },
]);


const displayedComments = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  let filteredComments = props.comments;

  if (activeFilter.value === 'latest') {
    filteredComments = [...filteredComments].sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
  } else if (activeFilter.value === 'withImages') {
    filteredComments = filteredComments.filter(comment => comment.picture?.length > 0);
  } else if (activeFilter.value === 'positive') {
    filteredComments = filteredComments.filter(comment => comment.score >= 4);
  } else if (activeFilter.value === 'negative') {
    filteredComments = filteredComments.filter(comment => comment.score <= 2);
  }

  return filteredComments.slice(start, end);
});

const totalComments = computed(() => {
  if (activeFilter.value === 'latest') {
    return props.comments.length;
  } else if (activeFilter.value === 'withImages') {
    return props.comments.filter(comment => comment.picture?.length > 0).length;
  } else if (activeFilter.value === 'positive') {
    return props.comments.filter(comment => comment.score >= 4).length;
  } else if (activeFilter.value === 'negative') {
    return props.comments.filter(comment => comment.score < 4).length;
  } else {
    return props.comments.length;
  }
});

const ratingComment = (rating) => {
  if (rating > 4.5) {
    return '超赞';
  } else if (rating > 4.2) {
    return '很棒';
  } else if (rating >= 4.0) {
    return '较好';
  } else {
    return '较差';
  }
};


function handlePageChange(page) {
  currentPage.value = page;
}

function applyFilter(filterType) {
  activeFilter.value = filterType;
  currentPage.value = 1; // 重置到第一页
}

function writeReview() {
  router.push('/write-review'); // 跳转到评价编写页面
}

function truncatedText(text) {
  // const maxLength = 230; // 最大显示字符数
  // if (text.length <= maxLength) {
    return text;
  // }
  // return text.slice(0, maxLength) + '...';
}

function toggleComment(comment) {
  comment.expanded = !comment.expanded;
}
</script>

<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&display=swap');
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css');

.rating-row-1 {
  padding: 30px 0px 24px;
  display: flex;
  flex-direction: row; /* 水平排列 */
  align-items: center;
  justify-content: space-between; /* 两端对齐 */
}
.score-box {
  padding: 0px 10px;
  background-color: #0e9aa7;
  border-radius: 20px 0px 20px 20px ;
  width: 70px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.sort-get-score {
  font-size: 30px;
  color: rgb(255, 255, 255);
  line-height: 40px;
  font-weight: bold;
}
.sort-all-score {
  font-size: 21px;
  color: rgba(255, 255, 255, 0.5);
  margin-left: 2px;
}

.rating-row-1 .entity-name {
  font-size: 36px;
  color: #0e9aa7;
  margin-left: 16px;
  font-weight: bold;
}

.rating-row-1 .total-reviews {
  font-size: 24px;
  color: rgb(15, 41, 77);
  text-align: right;
  line-height: 34px;
  font-weight: 600;
  margin-left: 8px;
}

.write-review-button {
  margin-left: auto;
}

.comments-section {
  font-family: "Noto Sans SC", sans-serif;
  margin: 0 0;
  text-align: left;
}

.rating-summary {
  margin-bottom: 20px;
}

.rating-score {
  font-size: 24px;
  font-weight: 700;
  color: #1890ff;
}

.filter-tabs span {
  font-size: 14px;
  line-height: 16px;
  color: rgb(15, 41, 77);
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  user-select: none;
  margin: 0px 16px 16px 0px;
  background: rgb(245, 247, 250);
}

.filter-tabs span.active {
  background: #333; /* 哑光黑色背景 */
  color: ivory; /* 象牙白色字体 */
}

.filter-tabs span:hover {
  color: #1890ff;
}

.comments-list {
  margin-bottom: 20px;
  margin-top: 24px;
}

.comment {
  display: flex;
  flex-direction: row;
  margin-bottom: 20px;
  
}

.comment-header {
  display: flex;
  align-items: top;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 15px;
  object-fit: cover;
}

.username {
  width: 60px;
  font-size: 16px;
  color: rgb(15, 41, 77);
  cursor: pointer;
  margin-top: 10px;
  margin-right: 30px;
}

.comment-body {
  display: flex;
  flex-direction: column;
  width: 100%;
  margin-top: 10px;
}

.rating-comment {
  display: flex;
  align-items: center;
}

.rating-box {
    background-color: rgba(51, 51, 51, 0.8); 
    color: #fff;
    padding: 0 10px;
    border-radius: 20px; /* 两边是半圆的圆角矩形 */
    display: inline-block;
    margin-right: 20px;
  }

.rating-comment-text {
  font-weight: 700;
  color: #1890ff;
}

.comment-text {
  margin-bottom: 10px;
  color: #000;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
}

.comment-text.expanded {
  -webkit-line-clamp: unset;
  line-clamp: unset;
}

.toggle-text {
  color: #1890ff;
  cursor: pointer;
  margin-bottom: 10px;
}

.attached-images {
  display: flex;
  gap: 5px;
  margin-top: 10px;
  margin-bottom: 10px;
}

.thumbnail {
  width: 80px;
  height: 80px;
  object-fit: cover;
  cursor: pointer;
}

.like-and-time {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.like-button {
  color: #999;
  cursor: pointer;
}

.like-button i {
  margin-right: 5px;
  border-radius: 50%;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.like-button i:hover {
  transform: translateZ(5px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.timestamp {
  font-size: 12px;
  color: #999;
}

hr {
  border: none;
  border-top: 1px solid #eee;
  margin: 20px 0;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
.child-comments {
  margin-left: 40px;
  padding-left: 20px;
  border-left: 2px solid #eee;
  margin-top: 10px;
}

.child-comment {
  margin-bottom: 20px;
}

</style>